<?php
// +----------------------------------------------------------------------
// | Author: wyd
// +----------------------------------------------------------------------
// | Date: 2025/7/8
// +----------------------------------------------------------------------

// [ 应用入口文件 ]
declare(strict_types=1);

use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;


//若某个类明明存在却提示not found  执行 composer dump-auto
require_once __DIR__ . '/../vendor/autoload.php';

require_once __DIR__ .'/app/config/define.php';


//***********************************************
//第一版，这些代码封装到了requestmapping中
$dispatcher = FastRoute\simpleDispatcher(function (FastRoute\RouteCollector  $r) {
    $r->addRoute('GET', '/test', function (){
        return 'mytest';
    });
});
//***********************************************

$http = new Server('0.0.0.0', 9501);

$http->on('Request', function (Request $request, Response $response) use ($dispatcher) {
    $myRequest = \My\core\http\Request::init($request);
    $routeInfo = $dispatcher->dispatch($myRequest->method(), $myRequest->uri());
    switch ($routeInfo[0]) {
        //$routeInfo,[]
        case FastRoute\Dispatcher::NOT_FOUND:
            // ... 404 Not Found
            $response->status(404);
            $response->end();
            break;
        case FastRoute\Dispatcher::METHOD_NOT_ALLOWED:
            $allowedMethods = $routeInfo[1];
            $response->status(405);
            $response->end();
            // ... 405 Method Not Allowed
            break;
        case FastRoute\Dispatcher::FOUND:
            $handler = $routeInfo[1];

            //$handler() 响应的是 addroute的第三个参数，是闭包;
            $response->end($handler());
            //$vars = $routeInfo[2];
            // ... call $handler with $vars
            break;
    }
});

$http->start();
